import { BaseView, addDomEvents, addHubEvents } from '../base';
import { first, append } from 'mvdom';
import { mom, now, formatDate } from 'ts/utils-date';
import { getDueDateUnitsInPeroid } from 'ts/service-unit';
import { render } from 'ts/render';



export class StatsDueDateView extends BaseView {


	private get filters() {
		const startDateInputEl = <HTMLInputElement>first(this.el, "input[name='startDate']")!;
		const endDateInputEl = <HTMLInputElement>first(this.el, "input[name='endDate']")!;
		let startDate, endDate;
		if (startDateInputEl.value) {
			startDate = mom(startDateInputEl.value);
		}

		if (endDateInputEl.value) {
			endDate = mom(endDateInputEl.value);
		}
		return { startDate, endDate };
	}

	//#region    ---------- View Events ---------- 
	events = addDomEvents(this.events, {
		"click; .search": (evt: any) => {
			this.refresh();
		}
	});
	//#endregion ---------- /View Events ----------

	async postDisplay() {
		this.renderDate();
	}

	private async refresh() {
		const filters = this.filters;
		const result = await getDueDateUnitsInPeroid(filters.startDate, filters.endDate);
		const tableFrag = render("StatsDueDateView-table", { items: result.unitSnapshots });
		append(first(this.el, ".section-results")!, tableFrag, "empty");
	}

	private renderDate() {
		const startDate = now();
		const endDate = now().add(1, "years").month(0).date(0);

		const startDateInputEl = <HTMLInputElement>first(this.el, "input[name='startDate']")!;
		const endDateInputEl = <HTMLInputElement>first(this.el, "input[name='endDate']")!;
		startDateInputEl.value = formatDate(startDate);
		endDateInputEl.value = formatDate(endDate);
	}
}

